$(function() {
    //主流程对象
    var mainCtrl = avalon.define({
        $id: "mainController",
        storeCode: "",
        cityCode: "",
        search: function() {
        	var type = "",code="";
			var currentType = $('.arrow_d').html();
        	if(currentType == '门店'){
        		//mainCtrl.storeCode = $("#magicStore .m-id").val();
				type = "0";
            	code = mainCtrl.storeCode;
        	}else{
        		//mainCtrl.cityCode = $("#magicCity .m-id").val();
				type = "1";
            	code = mainCtrl.cityCode;
        	}
            
            if(!code){
            	PLATFORM.showTips("error", "请选择"+currentType);	
            	return;
            }
            opts.settings.searchParam = {
                "pageNo": 1,
                "pageSize": 1000,
                "code":code,
                "type":type
            };
            
            exptTable.search(opts.settings.searchParam);
        },
        //切换是门店还是城市
        showOption: function(){
        	var currentType = $('.arrow_d').html();
        	if(currentType == '门店'){
        		$('.options').show().html('城市');
        	}else{
        		$('.options').show().html('门店');
        	}
        },
        changeType:function(){
        	var html = $('.options').html();
        	$('.arrow_d').html(html);
        	$('.options').hide();
        	if(html == '门店'){
        		$('#magicCity').hide();
        		$('#magicStore').show();
        	}else{
        		$('#magicCity').show();
        		$('#magicStore').hide();
        	}
        	
        },
        configActivity:function(row){
        	configActivity(row);
        }
        
    });
   
    //表格实例化
    var exptTable = null;
    var opts = {
        targetId: "exptTable",
        templateId: "tableActivity",
        settings: {
            url: DI.queryActivityList,
            ajaxType: "json",
            sourceInterface: {
                INum: "totalSize",
                IData: "records"
            },
            paginationIndexName: {
                "peerpageRows": "pageSize",
                "currentPage": "pageNo"
            }
        }
    };

    var magicCity = $('#magicCity').magicSuggest({
        renderer: function(city) {
            return city.cityName;
        },
        valueField:"cityCode",
        displayField:"cityName",
        placeholder: "请选择城市",
        maxSelection:1,
        autoSelect:true,
        required: true,
        selectionStacked: true,
        expandOnFocus: true,
        selectionRenderer: function(city) {
            return city.cityName;
        }
    });
    
    var magicStore = $('#magicStore').magicSuggest({
        renderer: function(data) {
            return data.name;
        },
        placeholder: "选择门店编号/名称",
        required: true,
        selectionStacked: true,
        expandOnFocus: true,
        selectionRenderer: function(data) {
            return data.name;
        }
    });
    
    
    
    
    function getAllStores() {
        $(".loadData").show();
        $.ajax({
            type: "post",
            dataType: "json",
            url: DI.getAllStoreInfo,
            success: function(data) {
                $(".loadData").hide();
                var allStoreData = data.data;
                var alljsonData = [];
                for(var i = 0; i < allStoreData.length; i++) {
					if(allStoreData[i].level == 3) {
					    alljsonData.push({
                            id: allStoreData[i].id,
                            name: allStoreData[i].id + "-" + allStoreData[i].text
                        });
					}
                }
                magicStore.setData(alljsonData);
                $(magicStore).on(
                    'selectionchange',
                    function(e, cb, s) {
                        var str = cb.getValue();
                        mainCtrl.storeCode = str[0];
                    });
            },
            error: function(err) {
                console.log(err);
            }
        });
    }
    
    function getAllCity() {
        $.ajax({
            type: "post",
            dataType: "json",
            url: DI.getCityInfo,
            success: function(data) {
                var allCityInfo = data.data;
                var alljsonData = [];
                for(var i = 0; i < allCityInfo.length; i++) {
                	if(!allCityInfo[i].cityCode){
                		continue;
                	}
	            	alljsonData.push({
	                	cityCode: allCityInfo[i].cityCode,
	                	cityName: allCityInfo[i].cityCode + "-" + allCityInfo[i].cityName
	             	});
                 }
                magicCity.setData(alljsonData);
                $(magicCity).on(
                    'selectionchange',
                    function(e, cb, s) {
                        var str = cb.getValue();
                        mainCtrl.cityCode = str[0];
                    });
                
            },
            error: function(err) {
                console.log(err);
            }
        });
    }
    
	
    
    getAllStores();
    getAllCity();
    
    
    //初始化时需要选中第一个进行查询
    if(exptTable == null) {
    	opts.settings.searchParam = {
            "pageNo": 1,
            "pageSize": 1000 //默认不分页，查询所有活动（基本没几个进行中的促销活动的）
        };
    	var currentType = sessionStorage.getItem('currentType');
        if(currentType){
        	$('.options').html(currentType);
        	mainCtrl.changeType();
        	var type = (currentType == '门店') ? '0' : '1';
        	var code = sessionStorage.getItem('currentCode');
        	var currentName = sessionStorage.getItem('currentName');
        	opts.settings.searchParam.type = type;
        	opts.settings.searchParam.code = code;
        	if(type=='0'){
        		magicStore.setValue([{'id':code,'name':currentName}]);
        	}else{
        		magicCity.setValue([{'cityCode':code,'cityName':currentName}]);
        	}
        	
        	sessionStorage.removeItem('currentType');
        	sessionStorage.removeItem('currentCode');
        	sessionStorage.removeItem('currentName');
        }
        
        exptTable = SwiftUI.swiftTable.getInstance(opts);
    }
    avalon.scan();
    
    
	
    
});
$("body").on("click",function(e){
	var elem = e.srcElement||e.target;
	if($(elem).hasClass('arrow_d') || $(elem).hasClass('options')){
		return;
	}
	$('.options').hide();
})


function configActivity(row){
	var currentType = $('.arrow_d').html();
	if(currentType == '门店'){
    	code = $("#magicStore .m-id").val();
	}else{
    	code = $("#magicCity .m-id").val();
	}
	var currentName = $.trim($('.ms-sel-item').text());
	sessionStorage.setItem('currentType',currentType);
	sessionStorage.setItem('currentCode',code);
	sessionStorage.setItem('currentName',currentName);
	
	delete row.$events;
	var value = JSON.stringify(row);
	sessionStorage.setItem('key_exchange',value);
	window.location.href = 'configActivity.html';
}